const app = getApp()
const util = require('../../utils/util.js')
Page({
    data: {
        userinfo: {},
        longitude: 116.404556,
        latitude: 41.915156,
        seller_address: false, //商家信息是否出现
        markers: [],
        tel: '',
        scale: 16,
        isClick: true,
        nearySeller: [], //所有附近商家
        seller: {}
    },
    // 页面加载
    onLoad(query) {
        my.showLoading({
            content: 'loading...'
        });
        // 获取用户信息
        this.getUseInfo();


        // 开始获取定位信息
        this.getLocation();

        my.hideLoading();

        let deviceSn = app.globalData.deviceSn;
        if (deviceSn) {
            // 存在公共的设备SN，那么用户是扫码租借进入
            this.checkDeviceType(deviceSn);
        }
    },
    // ========================= 判断设备类型 =======================
    checkDeviceType(sn) {
        my.showLoading({
            content: 'loading...'
        });
        let that = this;
        app.globalData.deviceSn = "";
        util.httpRequest('/checkDeviceType', {
            sn: sn
        }, function (res) {
            my.hideLoading();
            if (res.code == 1) {
                switch (res.data.type) {
                    case 0:
                        // 机柜设备租借
                        that.borrowCabinet(sn);
                        break;
                    case 1:
                        // 充电线租借
                        that.lineBorrow(sn);
                        break;
                    default:
                        break;
                }
            }
        })
    },
    // ========================= 获取用户信息 ====================================
    getUseInfo() {
        let that = this;
        util.httpRequest('/getInfo', {}, function (res) {
            if (res.code == 1) {
                that.setData({
                    userinfo: res.data.user
                })
            }
        })
    },
    // ========================= 开始获取定位信息 ====================================
    getLocation() {
        let that = this;
        my.getLocation({
            success(res) {
                that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude
                });
                app.globalData.longitude = res.longitude;
                app.globalData.latitude = res.latitude;
                // 获取附近的商家
                that.getNearyShopInfo(res.longitude, res.latitude);
            }
        });
    },
    // ========================= 获取附近商家信息 ====================================
    getNearyShopInfo(longitude, latitude) {
        my.showLoading({
            content: 'loading...'
        });
        let that = this;
        util.httpRequest('/getShopList', {
            longitude: longitude,
            latitude: latitude,
            isList: 0
        }, function (res) {
            my.hideLoading();
            if (res.code == 1) {
                that.setData({
                    nearySeller: res.data.list,
                    tel: res.data.tel
                })
                let arr = [];
                if (res.data.list != null) {
                    for (let s of res.data.list) {
                        arr.push({
                            id: s.id,
                            width: s.width,
                            height: s.height,
                            longitude: s.lng,
                            latitude: s.lat,
                            iconPath: s.iconPath
                        })
                    }
                    console.log(arr);
                    that.setData({
                        markers: arr
                    })
                }

            }
        })
    },
    //  ==================== 点击查看附近商家信息 ================================
    goNearbyShops() {
        let that = this;
        // 隐藏商家信息
        that.hideSeller();
        let dat = {
            longitude: that.data.longitude, //经度
            latitude: that.data.latitude // 纬度
        };
        my.navigateTo({
            //跳转附近商家界面
            url: '../nearby/nearby?localtion=' + JSON.stringify(dat)
        });
    },

    // =================== 隐藏商家信息 ===================================
    hideSeller() {
        this.setData({
            seller_address: false
        })
    },
    // ==================== 跳转到使用帮助页面 =============================
    goToHelp() {
        //隐藏商家信息
        this.hideSeller();
        //跳转帮助页面
        my.navigateTo({
            url: '../help/help'
        });
    },
    // ==================== 跳转到个人用户页面 ==============================
    goToUser() {
        //隐藏商家信息
        this.hideSeller();
        //跳转用户界面
        my.navigateTo({
            url: '../user/user'
        });

        // my.navigateTo({
        //   url: '../usedDetails/usedDetails'
        // });
        // my.navigateTo({
        //   url: '../help/help'
        // });
        //  my.navigateTo({
        //   url: '../linePassword/linePassword'
        // });
        // my.navigateTo({
        //   url: '../borrowStatus/borrowStatus'
        // });
        // my.navigateTo({
        //   url: '../lineBorrow/lineBorrow'
        // });
        // my.navigateTo({
        //     url: '../onLoan/onLoan'
        // });
        // my.navigateTo({
        //   url: '../borrowDetail/borrowDetail'
        // });
    },
    // ==================== 搜索附近充电宝 ==============================
    searchAddress() {
        let that = this;
        my.chooseLocation({
            success: function (res) {
                that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude
                })
                app.globalData.longitude = res.longitude;
                app.globalData.latitude = res.latitude;
            }
        });
    },
    // 移动地图
    regionchange(e) {
        let that = this;
        if (e.type == 'end') {
            that.setData({
                scale: e.scale
            });
            that.mapCtx.getCenterLocation({
                success(res) { //获取移动地图之后的中心坐标
                    that.setData({
                        longitude: res.longitude,
                        latitude: res.latitude
                    })
                    app.globalData.longitude = res.longitude;
                    app.globalData.latitude = res.latitude;
                    that.getNearyShopInfo(res.longitude, res.latitude)
                }
            });
        }
    },
    // =================== 重置定位 =======================
    resetLocation() {
        this.mapCtx.moveToLocation();
    },
    // =================== 拨打电话联系客服 =======================
    makePhoneCall(e) {
        let tel = e.currentTarget.dataset.tel;
        my.makePhoneCall({number: tel.toString()});
    },

    // =================== 点击商家所在位置 =======================
    markertaps(e) {
        let that = this;
        that.setData({
            seller_address: true
        })
        for (let s of that.data.nearySeller) {
            if (s.id == e.markerId) {
                that.setData({
                    seller: s
                })
                return
            }
        }
    },
    // =================== 跳转到商家（场地）页面 =======================
    goToShop() {
        let that = this;
        my.navigateTo({
            url: '../shop/shop?id=' + that.data.seller.id
        });
    },
    // =================== 跳转到商家（场地）页面 =======================
    toScanCode() {
        //调用二维码扫码功能
        let that = this;
        if (that.data.isClick) {
            that.setData({
                isClick: false
            })
            my.scan({
                type: 'qr',
                hideAlbum: true,
                success: function (res) {
                    if (res.qrCode) {
                        let url = res.qrCode;
                        let sn = url.split('/').pop();
                        // console.log("扫码对应的SN=>" + sn);
                        // 校验设备类型
                        util.httpRequest('/checkDeviceType', {
                            sn: sn
                        }, function (res) {
                            if (res.code == 1) {
                                switch (res.data.type) {
                                    case 0:
                                        // 机柜设备租借
                                        that.borrowCabinet(sn);
                                        break;
                                    case 1:
                                        // 充电线租借
                                        that.lineBorrow(sn);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                    } else {
                        my.showToast({
                            content: '扫码失败',
                            type: 'none'
                        });
                    }
                },
                complete: function () {
                    that.setData({
                        isClick: true
                    })
                }
            });
        }
    },
    // ============================ 扫码租借机柜设备(第一步骤) ==============================
    borrowCabinet(sn) {
        my.showLoading({
            content: 'loading...'
        });
        util.httpRequest('/deviceFirstStep', {
            sn: sn
        }, function (res) {
            my.hideLoading();
            switch (res.code) {
                case 1:
                    // 跳转到租借充电宝界面
                    my.navigateTo({
                        url: '../borrow/borrow?data=' + JSON.stringify(res.data)
                    });
                    break;
                default:
                    my.showToast({
                        content: res.msg,
                        type: 'none'
                    });
                    break;
            }
        })
    },
    // ================================= 扫码租赁密码线 ================================
    lineBorrow(sn) {
        my.showLoading({
            content: 'loading...'
        });
        util.httpRequest('/lineScan', {
            sn: sn
        }, function (res) {
            my.hideLoading();
            switch (res.code) {
                case 1:
                    // 租借
                    my.navigateTo({
                        url: '../lineBorrow/lineBorrow?data=' + JSON.stringify(res.data)
                    });
                    break;
                case 2:
                    // 充电线已有订单
                    my.navigateTo({
                        url: '../linePassword/linePassword?data=' + JSON.stringify(res.data)
                    });
                    break;
                case 3:
                    // 免费用户租借充电线，默认套餐1
                    my.navigateTo({
                        url: '../linePassword/linePassword?data=' + JSON.stringify(res.data)
                    });
                    break;
                default:
                    my.showToast({
                        content: res.msg,
                        type: 'none'
                    });
                    break;
            }
        })
    },

    onReady() {
        // 页面加载完成
        this.mapCtx = my.createMapContext('myMap')
    },
    onShow() {
        // 页面显示
    },
    onHide() {
        // 页面隐藏
    },
    onUnload() {
        // 页面被关闭
    },
    onTitleClick() {
        // 标题被点击
    },
    onPullDownRefresh() {
        // 页面被下拉
    },
    onReachBottom() {
        // 页面被拉到底部
    },
    onShareAppMessage() {
        // 返回自定义分享信息
        return {
            title: 'My App',
            desc: 'My App description',
            path: 'pages/index/index',
        };
    },
});
